package com.jeomo.common.log.service.impl;

import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.log.entity.SysLog;
import com.jeomo.common.log.mapper.SysLogMapper;
import com.jeomo.common.log.service.ILogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author:Jackpot
 * @create 2020-08-14 11:24
 * 系统日志服务
 */
@Service
public class LogServiceImpl extends BaseServiceImpl<SysLogMapper, SysLog>
        implements ILogService {

    private static Logger logger = LoggerFactory.getLogger(LogServiceImpl.class);
    private static final LinkedBlockingQueue<SysLog> logQueue = new LinkedBlockingQueue<SysLog>();

    @Resource
    private SysLogMapper sysLogMapper;

    @Override
    public void recordLog(SysLog sysLog) {
        logQueue.offer(sysLog);
    }

    @PostConstruct
    private void writeLog() {
        new Thread(new LogTask(), "log-record").start();
        logger.info("系统日志记录器初始化完毕.");
    }

    private class LogTask implements Runnable {

        @Override
        public void run() {
            for (;;) {
                try {
                    SysLog log = logQueue.take();
                    sysLogMapper.insert(log);

                } catch (Exception e) {
                    logger.error("系统日志记录出现异常", e);
                }
            }
        }
    }

}
